package com.bizmda.bizsip.source.api;

import lombok.Getter;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@Getter
public class AppServiceClientProxy<T> implements InvocationHandler, Serializable {

    private final Class<T> mapperInterface;
    private final Map<Method, AppServiceClientMethod> methodCache;
    private String bizServiceId;

    public AppServiceClientProxy(Class<T> mapperInterface, String bizServiceId) {
        this.mapperInterface = mapperInterface;
        this.methodCache = new HashMap<>();
        this.bizServiceId = bizServiceId;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (Object.class.equals(method.getDeclaringClass())) {
            try {
                return method.invoke(this, args);
            } catch (Throwable t) {

            }
        }
        final AppServiceClientMethod serviceClientMethod = cachedMapperMethod(method);

        return serviceClientMethod.execute(args);
    }

    private AppServiceClientMethod cachedMapperMethod(Method method) {
        AppServiceClientMethod appServiceClientMethod = methodCache.get(method);
        if (appServiceClientMethod == null) {
            appServiceClientMethod = new AppServiceClientMethod(method, this);
            methodCache.put(method, appServiceClientMethod);
        }
        return appServiceClientMethod;
    }

}
